package com.heima.controller;


import com.heima.Result;
import com.heima.context.ResidentContext;
import com.heima.domain.po.MessageBoard;
import com.heima.domain.query.MessageBoardQuery;
import com.heima.exception.DIYException;
import com.heima.service.IMessageBoardService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 * 在线留言表 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-08-05
 */
@Tag(name = "在线留言相关接口")
@RestController
@RequestMapping("/resident/message-board")
public class MessageBoardController {
    @Autowired
    private IMessageBoardService messageBoardService;

    @Operation(summary = "分页查询所有人的留言")
    @GetMapping("/page")
    public Result page(MessageBoardQuery messageBoardQuery) {
        return messageBoardService.findByPage(messageBoardQuery);
    }
    @Operation(summary = "分页查询自己的留言")
    @GetMapping("/my-page")
    public Result myPage(MessageBoardQuery messageBoardQuery) {
        return messageBoardService.MyfindByPage(messageBoardQuery);
    }

    @Operation(summary = "新增留言")
    @PostMapping("/add")
    public Result add(@RequestBody MessageBoard messageBoard) {
        if (ResidentContext.getCurrentId() == null) {
            throw new DIYException("请先登录");
        }
        Long userId = ResidentContext.getCurrentId();
        messageBoard.setUserId(userId);
        messageBoard.setCreateTime(LocalDateTime.now());
        messageBoard.setUpdateTime(LocalDateTime.now());
        messageBoardService.save(messageBoard);
        return Result.success();
    }
    @Operation(summary = "删除留言")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        if (ResidentContext.getCurrentId() == null) {
            throw new DIYException("请先登录");
        }
        Long userId = ResidentContext.getCurrentId();
        messageBoardService.lambdaUpdate()
                .eq(MessageBoard::getId, id)
                .eq(MessageBoard::getUserId, userId)
                .remove();
        return Result.success();
    }
}
